﻿using FastEndpoints;
using TodoList.Data;

namespace TodoList.FastEndpoints.Features.Delete;

internal sealed class Endpoint(ApplicationDbContext db) : Endpoint<Request, Response>
{
    public override void Configure()
    {
        Delete("/api/todoList/{id:int}");
        AllowAnonymous();
    }

    public override async Task HandleAsync(Request req, CancellationToken ct)
    {
        var todo = await db.TodoItems.FindAsync([req.Id], cancellationToken: ct);
        if (todo is null)
        {
            await SendAsync(new Response { Message = "Todo item not found." }, cancellation: ct);
            return;
        }
        db.TodoItems.Remove(todo);
        await db.SaveChangesAsync(ct);
        await SendAsync(new Response { Message = "Todo item deleted successfully." }, cancellation: ct);
    }
}
